<template>
  <div>
    <r-search :searchForm="searchForm" :searchHandle="searchHandle" :searchData="searchData" />
    <r-table :tableHandles="tableHandles" :isSelection="false" :isIndex="false" :isPagination="true"
      :tableData="tableData" :tableCols="tableCols" :tablePage="tablePage" :isHandle="true" @refresh="init()">

    </r-table>
    <!-- 编辑按钮打开的表单 -->
    <r-form :formRules="formRules" :formHandle="formHandle" :formData="formData" :formCols="formCols" ref="elForm"
      labelWidth="250px" dialogWidth="800px" :isHandle="true">

      <div v-show="isType" v-for="(item, index) in mealBaseRateEntities" :key="index" style="margin-bottom: 10px;">
        <div style="position: relative;width: 75%;left:20%">
          <span style="margin-right: 16px;">充电功率(瓦)</span>
          <el-input v-model="item.rateOfWork" placeholder="请输入" size="small" style=" width: 15%" />
          <span style="margin-right: 20px;margin-left: 70px;">费用(元)</span>
          <el-input v-model="item.cost" placeholder="请输入" size="small" style=" width: 20%" />
          <i class="el-icon-delete" @click="deleteInput(item, index)" style="color:red;fontSize:25px"></i>

        </div>

      </div>
      <div>
        <i v-show="isType" class="el-icon-circle-plus-outline" @click="addInput"
          style="color:blue;fontSize:25px;margin-left: 605px;"></i>
        <!-- <i v-show="isType" class="el-icon-refresh-right" @click="qingkongInput(item, index)"
          style="color:blue;fontSize:25px;margin-left: 645px;"></i> -->
      </div>






    </r-form>



    <!-- <div>
      <el-dialog title="编辑" :visible.sync="dialogFormVisible">
        <el-form :model="formDatas">
          <el-form-item label="套餐名称" label-width="80px">
            <el-input v-model="formDatas.mealName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="套餐类型" label-width="80px">
            <el-select v-model="formDatas.type" placeholder="套餐类型">
              <el-option label="按时间收费" value="1"></el-option>
              <el-option label="按电量收费" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收费标准（每小时/每度电）" :label-width="formLabelWidth">
            <el-input v-model="formDatas.mealName" autocomplete="off"></el-input><span>元</span>
          </el-form-item>
          <el-form-item label=" 充电功率（瓦）" :label-width="formLabelWidth">
            <el-input v-model="cost" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="使用费用" :label-width="formLabelWidth">
            <el-input v-model="rateOfWork" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
        </div>
      </el-dialog>
    </div> -->
    <!-- 详情页 -->
    <Associated_devices :res="Associated_devices_data" v-if="Associated_devices_data.show"
      v-on:Associated_devices_call="Associated_devices_call"></Associated_devices>
  </div>
</template>
<script>
import Associated_devices from "./cus/Associated_devices";
export default {
  components: {
    Associated_devices
  },
  data() {
    return {
      // formDatas: {
      //   mealName: '',
      //   type: '',
      //   price: '',
      //   mealBaseRateEntities: [
      //     {
      //       rateOfWork: "", //充电功率（瓦）
      //       cost: "", //费用 (元)
      //     }
      //   ]
      // },
      mealBaseRateEntities: [],//接收按电量收费的数据
      formData: {
        mealBaseRateEntities: [],
        mealName: "",
        price: '',
        limitAmount:'',
        type: '',
        rateOfWork: [], //充电功率（瓦）
        cost: [], //费用 (元)
      },
      formLabelWidth: '120px',
      dialogFormVisible: false,
      newDianliang: 1,
      gonglipicess: {},
      cost: '',
      rateOfWork: '',
      isType: false,
      Associated_devices_data: {
        show: false,
        id: ''
      },
      searchData: {
        type: '',
      },
      // 请选择套餐类型下拉框
      searchForm: [
        {
          type: 'select',
          prop: 'type',
          placeholder: '套餐类型',
          width: 150,
          options: [
            { label: '按时间收费', value: 1 },
            { label: '按功率收费', value: 2 },
          ]
        },
      ],
      // 搜索按钮
      searchHandle: [
        {
          label: '搜索',
          type: 'success',
          icon: 'el-icon-search',
          handle: e => this.init()
        }
      ],
      // 新增套餐 按钮
      tableHandles: [
        {
          label: "新增套餐",
          type: "primary",
          handle: e => this.elFormVisible(
            // 按电量收费初始化
            this.mealBaseRateEntities = [{
              rateOfWork: '', //充电功率（瓦）
              cost: '', //费用 (元)
            }]
          )
        }
      ],
      tableData: [],
      // 分页列表的格式
      tableCols: [
        {
          label: '序号',
          prop: 'id',
        },
        {
          label: '充电套餐名',
          prop: 'mealName',
        },
        {
          label: '套餐类型',
          prop: 'type',
          formatter: (row) => {
            if (row.type == 1) {
              return '按时间收费'
            } else if (row.type == 2) {
              return '按功率收费'
            }
          }
        },
        {
          label: '收费标准',
          prop: 'price'
        },
        {
          label: '关联设备',
          prop: 'deviceNum'
        },
        {
          label: '更新时间',
          prop: 'ctime'
        },
        {
          label: '启用状态',
          type: "switch",
          prop: 'status',
          values: [1, 2],
          change: (row) => this.changestate(row)
        },

        {
          label: '操作',
          type: "button",
          width: 300,
          btnList: [
            {
              label: '已关联设备',
              type: 'primary',
              handle: (row) => {
                this.Associated_devices_data.id = row.id;
                this.Associated_devices_data.show = true;
              }
            },
            {
              label: '编辑',
              type: 'primary',
              handle: (row) => this.elFormDetail(row)
              // handle: ((row) => {
              //   this.dialogFormVisible = true
              //   this.bianjiForm(row)
              // })
            },
            {
              label: '删除',
              type: 'primary',
              handle: (row) => this.del(row)
            },

          ]
        }

      ],
      // 分页的数量、页码与总条数
      tablePage: { limit: 10, page: 1, total: 0 },
      // 编辑页面的form表单的数据源

      // 编辑页面的form表单格式
      formCols: [
        { type: "input", label: "套餐名称", width: 350, prop: "mealName", },
        {
          type: "select", label: "套餐类型", width: 350, prop: "type", options: [
            { label: '按时间收费', value: 1 },
            { label: '按功率收费', value: 2 },
          ],
        },
        {
          type: "input", label: "收费标准（每小时）", width: 350, prop: "price", remark: '元',
          isShow: () => this.isType ? false : true,

        },
        {
          type: "input", label: "套餐使用最小金额", width: 350, prop: "limitAmount", remark: '元',
          isShow: () => this.isType ? false : true,

        },
        // {
        //   type: "input", label: "充电功率(瓦)", width: 350, prop: "rateOfWork",
        //   isShow: () => this.isType ? true : false,
        // },
        // {
        //   type: "input", label: "费用", width: 350, prop: "cost",
        //   isShow: () => this.isType ? true : false
        // },
        // {
        //   type: "select", label: "充电功率(瓦)", width: 350, prop: "rateOfWork",
        //   options: [{ label: '210', value: 1 }, { label: '220', value: 2 }, { label: '480', value: 3 }],
        //   isShow: () => this.isType ? true : false
        // },
      ],
      // 编辑页面form表单的消息提示
      formRules: {
        mealName: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        limitAmount: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择', trigger: 'blur' },
        ],
      },
      // 编辑页面的 确定 取消按钮
      formHandle: [
        {
          label: "取消",
          handle: e => this.elFormVisible(),
        },
        {
          label: "确定",
          type: "success",
          handle: e => this.elFormSubmit(),
        },

      ],
    };
  },
  methods: {
    // 从后台拿到分页列表的数据
    async init() {
      let parm = {
        ...this.searchData, ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      }
      let res = await this.apis.mealCharge_list(parm)
      if (res) {
        this.tableData = res.rows || [];
        this.tablePage.total = res.total
      }

    },
    // 按电量收费删除的办法
    async deleteInput(item, index) {
      let res = await this.apis.webMealBaseRateDel(item.id)
      console.log(res);
      if (this.mealBaseRateEntities.length <= 3) {
        this.$message({
          message: '添加按电量收费不得少于三条',
          type: 'error'
        })
        return false
      }
      this.mealBaseRateEntities.splice(index, 1)
    },
    // 按电量收费增加的办法
    addInput() {
      this.mealBaseRateEntities.push(
        {
          rateOfWork: '',
          cost: '',
        }
      )
    },
    // qingkongInput() {
    //   this.mealBaseRateEntities = this.mealBaseRateEntities.forEach((item) => {
    //     item.cost = '', item.rateOfWork = ''
    //   })
    // },
    // 编辑 按钮调用的方法
    async elFormDetail(row) {
      let res = await this.apis.webMealCharge(row.id)
      if (res.code == 200) {
        this.formData = res.data
        this.mealBaseRateEntities = res.data.mealBaseRateEntities
      }

      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key]
      })
      this.elFormVisible()
    },
    // 编辑 （新增）页面的确定按钮 调用的方法
    async elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(async (valid) => {

        if (valid) {
          // 当选中按电量收费时，要限制是否有三条
          if (this.newDianliang == 2) {
            if (this.mealBaseRateEntities.length < 3) {
              this.$message({
                message: '添加按电量收费不得少于三条',
                type: 'error'
              })
              return false
            }
            // else if (this.mealBaseRateEntities.length >= 3) {

            //   var arrs = this.mealBaseRateEntities.forEach((item) => {


            //   })
            //   if (arrs.length == 0) {
            //     console.log(111111111);
            //     alert(111111)

            //   }
            // }
          }
          // 把按电量收费数组this.mealBaseRateEntities与formData对象，组成新的对象，作为数据源，发送请求
          let mealBaseRateEntities = this.mealBaseRateEntities
          this.formData.mealBaseRateEntities = mealBaseRateEntities
          // 有id就是编辑的
          if (this.formData.id) {
            const res = await this.apis.mealCharge_update({ ...this.formData, });
          }
          // 没id就是新增的
          else {
            const res = await this.apis.mealCharge_save({ ...this.formData });
            // this.apis.MealBaseRate({ ...this.formData }).then((res) => {
            //   console.log(res);
            // })
          }

          this.init();
          this.elFormVisible()

        }
      })
    },
    // 删除按钮调用的方法
    del(row) {
      this.$confirm(`删除当前这条数据`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.apis.mealCharge_del({
          id: row.id
        });

        this.init();

        this.$message({
          message: '操作成功！',
          type: 'success'
        });

      })
    },
    // 启用状态按钮调用的方法
    async changestate(row) {

      const res = await this.apis.mealCharge_update({
        id: row.id,
        status: row.status
      });
      this.$message({
        message: '操作成功！',
        type: 'success'
      });
    },

    Associated_devices_call() {
      this.Associated_devices_data.show = false;
    }
  },
  watch: {
    "formData.type": {

      deep: true,
      handler: function (newV, oldV) {
        this.newDianliang = 1
        // 当套餐类型为2，即按电量收费
        if (newV == 2) {
          this.newDianliang = newV
          this.isType = true,//控制按电量收费时会出现的表单
            console.log(newV);
        } else {
          this.isType = false
        }
      }
    }
  },
  computed: {},
  mounted() {
    this.init()

  },
};
</script>
<style scoped lang='scss'>
.el-icon-search {
  margin-right: 10px;
}

.Tip {
  margin-left: 20px;

}
</style>
